package com.olive.filter;

import java.io.IOException;
import java.util.Objects;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import com.olive.constants.UserConstants;
import com.olive.dto.CaptchaImageVO;
import com.olive.handler.CommonLoginFailureHandler;

import cn.hutool.core.util.StrUtil;

@Component
public class CaptchaCodeFilter extends OncePerRequestFilter {
    
	@Autowired
    CommonLoginFailureHandler failureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        if (StrUtil.equals("/login2", httpServletRequest.getRequestURI()) &&
                StrUtil.equalsIgnoreCase("post", httpServletRequest.getMethod())) {
            try {
                //报错 直接传参httpServletRequest
                validated(new ServletWebRequest(httpServletRequest));
            } catch (SessionAuthenticationException e) {
                failureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
                return;
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    private void validated(ServletWebRequest request) {
        HttpSession session = request.getRequest().getSession();
        String kaptcha = request.getRequest().getParameter("kaptcha");
        CaptchaImageVO captchaImageVO = (CaptchaImageVO) request.getRequest().getSession().getAttribute(UserConstants.CAPTCHA_SESSION_KEY);
        if (Objects.isNull(captchaImageVO)) {
            throw new SessionAuthenticationException("验证码不存在");
        }
        if (captchaImageVO.isExpired()) {
            session.removeAttribute(UserConstants.CAPTCHA_SESSION_KEY);
            throw new SessionAuthenticationException("验证码已过期");
        }
        if (!StrUtil.equals(kaptcha, captchaImageVO.getText())) {
            throw new SessionAuthenticationException("验证码不匹配");
        }
        session.removeAttribute(UserConstants.CAPTCHA_SESSION_KEY);
    }
}
